using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SG3L_RAG.Application.DTOs;
using SG3L_RAG.Application.Interfaces;
using System.Security.Claims;

namespace SG3L_RAG.Api.Controllers;

/// <summary>
/// 认证控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly IAuthService _authService;
    private readonly IJwtService _jwtService;

    public AuthController(IAuthService authService, IJwtService jwtService)
    {
        _authService = authService;
        _jwtService = jwtService;
    }

    /// <summary>
    /// 用户登录
    /// </summary>
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginDto loginDto)
    {
        try
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            var result = await _authService.LoginAsync(loginDto);
            if (result == null)
                return Unauthorized(new { message = "用户名或密码错误" });

            return Ok(result);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = $"登录失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 用户注册
    /// </summary>
    [HttpPost("register")]
    public async Task<IActionResult> Register([FromBody] RegisterDto registerDto)
    {
        try
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            var result = await _authService.RegisterAsync(registerDto);
            return Ok(result);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = $"注册失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 验证Token
    /// </summary>
    [HttpPost("validate")]
    public async Task<IActionResult> ValidateToken([FromBody] RefreshTokenDto tokenDto)
    {
        try
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            var result = await _jwtService.ValidateTokenAsync(tokenDto.Token);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = $"Token验证失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 刷新Token
    /// </summary>
    [HttpPost("refresh")]
    public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenDto tokenDto)
    {
        try
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            var result = await _jwtService.RefreshTokenAsync(tokenDto.Token);
            if (result == null)
                return Unauthorized(new { message = "Token无效或已过期" });

            return Ok(result);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = $"刷新Token失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 获取当前用户信息（需要认证）
    /// </summary>
    [HttpGet("me")]
    [Authorize]
    public IActionResult GetCurrentUser()
    {
        try
        {
            var userInfo = _jwtService.GetUserFromClaims(User.Claims);
            if (userInfo == null)
                return Unauthorized(new { message = "无法获取用户信息" });

            return Ok(userInfo);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = $"获取用户信息失败: {ex.Message}" });
        }
    }

    /// <summary>
    /// 登出（客户端处理，服务端无需特殊处理）
    /// </summary>
    [HttpPost("logout")]
    [Authorize]
    public IActionResult Logout()
    {
        // JWT是无状态的，登出主要在客户端处理（删除Token）
        // 这里只是提供一个标准的登出端点
        return Ok(new { message = "登出成功" });
    }

    /// <summary>
    /// 检查管理员权限
    /// </summary>
    [HttpGet("check-admin")]
    [Authorize(Roles = "admin")]
    public IActionResult CheckAdmin()
    {
        return Ok(new { message = "您具有管理员权限", isAdmin = true });
    }

    /// <summary>
    /// 检查用户权限
    /// </summary>
    [HttpGet("check-user")]
    [Authorize(Roles = "user,admin")]
    public IActionResult CheckUser()
    {
        var role = User.FindFirst(ClaimTypes.Role)?.Value;
        return Ok(new { message = "您已通过身份验证", role = role });
    }
}
